/**
 * Copyright：2020，TLF工作室。
 */
package com.cqeec.netdisc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.openstack4j.api.OSClient.OSClientV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqeec.netdisc.model.User;
import com.cqeec.netdisc.service.UserService;
import com.cqeec.netdisc.util.OpenStackClientUtil;

/**
 * 注册控制器。
 * 
 * @author 唐礼飞
 * 
 * @date 2020-10-19 11:30:14
 *
 */

@Controller
@RequestMapping("/user/")
public class RegisterController {

	@Autowired
	private UserService userService;

	@RequestMapping("/register")
	public String gotoRegisterPage() {
		return "register";
	}

	@RequestMapping("/register/save")
	@ResponseBody
	public Map<String, Object> register(User user, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (user.getEmail() == null || "".equals(user.getEmail())) {
			map.put("code", 1);
			map.put("message", "请输入用户的电子邮箱！");
			return map;
		}
		if (user.getName() == null || "".equals(user.getName())) {
			map.put("code", 2);
			map.put("message", "请输入用户真实姓名！");
			return map;
		}
		if (user.getLoginName() == null || "".equals(user.getLoginName())) {
			map.put("code", 3);
			map.put("message", "请输入用户名！");
			return map;
		}
		if (user.getPassword() == null || "".equals(user.getPassword())) {
			map.put("code", 4);
			map.put("message", "请输入用户密码！");
			return map;
		}
		try {
			userService.save(user);
			// 在OpenStack上创建用户的容器
			OSClientV3 os = OpenStackClientUtil.getOSClient();
			os.objectStorage().containers().create(user.getLoginName());
			session.setAttribute("user", user);
			map.put("code", 0);
			map.put("message", "用户注册成功！");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 5);
			map.put("message", "用户注册失败！");
		}
		return map;
	}
}
